package com.jingbit.ai.helper;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.text.TextUtils;

import com.jingbit.ai.entities.MessageInfo;
import com.jingbit.ai.listener.IMsgListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by pansha on 2016/12/29. sms主要结构： _id => 短消息序号 如100 thread_id =>
 * 对话的序号 如100 address => 发件人地址，手机号.如+8613811810000 person =>
 * 发件人，返回一个数字就是联系人列表里的序号，陌生人为null date => 日期 long型。如1256539465022 protocol => 协议
 * 0 SMS_RPOTO, 1 MMS_PROTO read => 是否阅读 0未读， 1已读 status => 状态 -1接收，0 complete,
 * 64 pending, 128 failed type => 类型 1是接收到的，2是已发出 body => 短消息内容 service_center
 * => 短信服务中心号码编号。如+8613800755500 String[] projection = new String[]{"address",
 * "body"}; Cursor cursor = getContentResolver().query(uri, projection, "where
 * .." new String[]{"", ""}, "order by ..")
 */

@SuppressLint("NewApi")
public class SmsHelper extends ContentObserver {

    static final String SMS_URI_ALL = "content://sms/";
    final String SMS_URI_INBOX = "content://sms/inbox";
    final String SMS_URI_SEND = "content://sms/sent";
    final String SMS_URI_DRAFT = "content://sms/draft";
    final String SMS_URI_OUTBOX = "content://sms/outbox";
    final String SMS_URI_FAILED = "content://sms/failed";
    final String SMS_URI_QUEUED = "content://sms/queued";


    /**
     * 单例
     */
    private static SmsHelper instance;

    private static Context context;
    private static Cursor cursor;
    private static IMsgListener listener;

    /**
     * Creates a content observer.
     *
     * @param handler The handler to run {@link #onChange} on, or null if none.
     */
    public SmsHelper(Handler handler) {
        super(handler);
    }

    /**
     * 保证调用一次即可
     */
    public static void register(Context context) {
        SmsHelper.context = context;
        listener = (IMsgListener) context;
        if (instance == null) {
            instance = new SmsHelper(new Handler());
        }
        context.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, instance);
    }

    /**
     * 保证调用一次即可
     */
    public static void unregister() {
        context.getContentResolver().unregisterContentObserver(instance);
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Logger.log(this, "onChange", selfChange);
        handleUnreadMsg(Uri.parse(SMS_URI_INBOX));
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
        super.onChange(selfChange, uri);
        Logger.log(this, "onChange", selfChange, uri);
        handleUnreadMsg(uri);
    }

    private void handleUnreadMsg(Uri uri) {
        try {
            String where = "_id>? and read=?";
            cursor = context.getContentResolver().query(uri, new String[]{"*"}, where, new String[]{"-1", "0"},
                    "date desc");
            if (cursor != null) {
                if (cursor.moveToNext()) {
                    String body = cursor.getString(cursor.getColumnIndex("body"));
                    String _id = cursor.getString(cursor.getColumnIndex("_id"));
                    String address = cursor.getString(cursor.getColumnIndex("address"));
                    Logger.log(this, "onChange", "拦截到短信：body=" + body + ";_id=" + _id + ";address=" + address);
                    listener.onChange(_id, body, address);
                }
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null && !cursor.isClosed()) {
                cursor.close();
                cursor = null;
            }
        }
    }

    public static String getVerifyCode(String body) {
        if (TextUtils.isEmpty(body)) {
            return null;
        }
        body = getVerifyCode(body, 6);
        if (TextUtils.isEmpty(body)) {
            body = getVerifyCode(body, 4);
        }
        return body;
    }

    /**
     * 从短信字符窜提取验证码
     *
     * @param body   短信内容
     * @param length 验证码的长度 一般6位或者4位
     * @return 接取出来的验证码
     */
    public static String getVerifyCode(String body, int length) {
        // 首先([a-zA-Z0-9]{YZMLENGTH})是得到一个连续的六位数字字母组合
        // (?<![a-zA-Z0-9])负向断言([0-9]{YZMLENGTH})前面不能有数字
        // (?![a-zA-Z0-9])断言([0-9]{YZMLENGTH})后面不能有数字出现


//    获得数字字母组合
//    Pattern p = Pattern   .compile("(?<![a-zA-Z0-9])([a-zA-Z0-9]{" + YZMLENGTH + "})(?![a-zA-Z0-9])");

        //  获得纯数字
        Pattern p = Pattern.compile("(?<![0-9])([0-9]{" + length + "})(?![0-9])");

        Matcher m = p.matcher(body);
        if (m.find()) {
            System.out.println(m.group());
            return m.group(0);
        }
        return null;
    }

    public static void sendMsg(String phoneno, String content) {
        SmsManager manager = SmsManager.getDefault();
        ArrayList<String> messages = manager.divideMessage(content);
        for (String message : messages) {
            manager.sendTextMessage(phoneno, null, message, null, null);
        }
    }

    public static void getMessages(Context context, Handler.Callback callback) {
        ArrayList smsInfos = new ArrayList();
        String selection = null;
        String[] selectionArgs = null;
//        if (BaseApplication.lastUpload2 > 0) {
//            selection = CallLog.Calls.DATE + ">?";
//            selectionArgs = new String[]{String.valueOf(BaseApplication.lastUpload2)};
//        }
        ContentResolver cr = context.getContentResolver();
        Cursor cur = cr.query(Uri.parse(SMS_URI_ALL), new String[]{"*"}, selection, selectionArgs, "date desc");
        if (null != cur)
            if (cur.moveToFirst()) {
                int index_Address = cur.getColumnIndex("address");
                int index_Person = cur.getColumnIndex("person");
                int index_Body = cur.getColumnIndex("body");
                int index_Date = cur.getColumnIndex("date");
                int index_Type = cur.getColumnIndex("type");

                do {
                    String strAddress = cur.getString(index_Address);
                    String strbody = cur.getString(index_Body);
                    long longDate = cur.getLong(index_Date);
                    int intType = cur.getInt(index_Type);

                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date d = new Date(longDate);
                    String strDate = dateFormat.format(d);

                    String strType = "";
                    if (intType == 1) {
                        strType = "接收";
                    } else if (intType == 2) {
                        strType = "发送";
                    } else {
                        strType = "null";
                    }

                    MessageInfo msgInfo = new MessageInfo();
                    msgInfo.setPhoneno(strAddress);
                    msgInfo.setContent(strbody);
                    msgInfo.setDate(strDate);
                    msgInfo.setType(strType);
                    smsInfos.add(msgInfo);
//                    Logger.log("SMSHelper", strAddress, strbody, strDate, strType);
                } while (cur.moveToNext());
            }
        Message msg = Message.obtain();
        msg.obj = smsInfos;
        msg.what = 2;
        callback.handleMessage(msg);
    }
}
